package com.shawn.baseappbygroovydsl.ui.views

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class ScopeViewModel : ViewModel() {
    private val viewModelScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    private val _text = MutableLiveData<String>().apply {
        value = "This is slideshow Fragment"
    }
    val text: LiveData<String> = _text

    val userData: LiveData<Result<String>> = liveData {
//        emit(Result.Loading)
//        try {
//            val user = apiService.getUser(userId).await()
//            emit(Result.Success(user))
//        } catch (e: Exception) {
//            emit(Result.Error(e))
//        }
    }

    open class UiState {
        object Loading : UiState()
        data class Success(val data: String) : UiState()
        data class Error(val message: String) : UiState()
    }

    private val _uiState = MutableStateFlow<UiState>(UiState.Loading)
    val uiState: StateFlow<UiState> = _uiState.asStateFlow()

    fun loadDataWithFlow() {
        viewModelScope.launch {
            _uiState.value = UiState.Loading
            try {
                val data = fetchData()
                _uiState.value = UiState.Success(data)
            } catch (e: Exception) {
                _uiState.value = UiState.Error(e.message ?: "未知错误")
            }
        }
    }


    fun loadData() {
        viewModelScope.launch {
            val data = fetchData()
            _text.value = data
        }
    }

    private fun fetchData(): String {
        return "Data"
    }
}